package com.campus.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.campus.domain.po.Activity;
import com.campus.mapper.ActivityMapper;
import com.campus.service.ActivityService;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class ActivityServiceImpl extends ServiceImpl<ActivityMapper, Activity> implements ActivityService {

    @Override
    public Activity getActivityById(Integer id) {
        return this.getById(id);
    }

    @Override
    public Activity saveActivity(Activity activity) {
        // 如果活动已经存在，则更新活动，否则创建新活动
        QueryWrapper<Activity> wrapper = new QueryWrapper<>();
        wrapper.eq("name", activity.getName());
        Activity existingActivity = this.getOne(wrapper);

        if (existingActivity == null) {
            this.save(activity);
            return activity;
        } else {
            Integer id = existingActivity.getId();
            BeanUtils.copyProperties(activity, existingActivity);
            existingActivity.setId(id);
            this.updateById(existingActivity);
            return existingActivity;
        }
    }

    @Override
    public boolean deleteActivityById(Integer id) {
        return this.removeById(id);
    }

    @Override
    public Activity updateActivity(Activity activity) {
        this.updateById(activity);
        return this.getById(activity.getId());
    }

    @Override
    public List<Activity> getActivityList(String name, Integer status, int page, int size) {
        QueryWrapper<Activity> wrapper = new QueryWrapper<>();
        if (name != null && !name.isEmpty()) {
            wrapper.like("name", name); // 模糊查询活动名称
        }
        if (status != null) {
            wrapper.eq("status", status); // 根据活动状态筛选
        }
        wrapper.orderByDesc("created_time"); // 按照创建时间降序排序

        return this.page(new com.baomidou.mybatisplus.extension.plugins.pagination.Page<>(page, size), wrapper).getRecords();
    }
}
